import apiClient, { wrapApiCall } from './api';
import type {
  NetworkSummary,
  NetworkDetail,
  ApiResponse,
  ListResponse,
} from '../types/api';

// 网络管理API服务
export const networkService = {
  // 获取所有网络
  listNetworks: async (connectionId: string): Promise<NetworkSummary[]> => {
    const response = await wrapApiCall<ListResponse<NetworkSummary>>(apiClient.get('/networks', {
      params: { connection: connectionId }
    }));

    if (!response.networks) {
      throw new Error('网络列表响应数据为空');
    }
    
    return response.networks;
  },

  // 获取网络详情
  getNetworkDetail: async (connectionId: string, networkName: string): Promise<NetworkDetail> => {
    const response = await wrapApiCall<NetworkDetail>(apiClient.get('/network', {
      params: {
        connection: connectionId,
        name: networkName
      }
    }));
    
    return response;
  },

  // 创建网络
  createNetwork: async (connectionId: string, xmlConfig: string): Promise<void> => {
    await wrapApiCall<ApiResponse>(apiClient.post('/networks', xmlConfig, {
      params: { connection: connectionId },
      headers: {
        'Content-Type': 'application/json',
      },
    }));
  },

  // 删除网络
  deleteNetwork: async (connectionId: string, networkName: string): Promise<void> => {
    await wrapApiCall<ApiResponse>(apiClient.delete('/network', {
      params: { 
        connection: connectionId,
        name: networkName 
      }
    }));
  },

  // 启动网络
  startNetwork: async (connectionId: string, networkName: string): Promise<void> => {
    await wrapApiCall<ApiResponse>(apiClient.post('/network/start', null, {
      params: { 
        connection: connectionId,
        name: networkName 
      }
    }));
  },

  // 停止网络
  stopNetwork: async (connectionId: string, networkName: string): Promise<void> => {
    await wrapApiCall<ApiResponse>(apiClient.post('/network/stop', null, {
      params: { 
        connection: connectionId,
        name: networkName 
      }
    }));
  },
};

export default networkService;